//
//  OwlWCFacility.m
//  Owl
//
//  Created by Tianzhou on 09-2-24.
//  Copyright 2009 Tianzhou Software Inc.. All rights reserved.
//

#import "OwlWCFacility.h"
#import "OwlSupport.h"
#import "OwlPreferenceKeys.h"
#import "GTMScriptRunner.h"

@implementation WCDataHolder

@synthesize fileURL = fileURL_;
@synthesize lineCount = lineCount_;
@synthesize wordCount = wordCount_;
@synthesize byteCount = byteCount_;

@end

@implementation OwlWCFacility

const NSString *const kTranslatorPath = @"/Projects/Local_WorkingCopy/Owl_WorkingCopy/Utility/WCToPlistTranslator/build/Debug/WCToPlistTranslator"; 
const NSString *const kWCScriptPath = @"/Projects/Local_WorkingCopy/Owl_WorkingCopy/Utility/wc_code.sh";

+ (int)gatherWCData:(NSArray **)wcData_o
		  UnderPath:(NSString *)path
{
#if USE_SHELL
	NSString *tempFileURL = [[NSBundle mainBundle] resourcePath];
	tempFileURL = [tempFileURL stringByAppendingPathComponent:@"tmp"];
	
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	NSString *suffixList = [userDefaults objectForKey:kOwlSuffixListKey];
	NSArray *interestedFileExts = [suffixList componentsSeparatedByString:@";"];
	NSString *fileExts = [NSString string];

	for (NSString *ext in interestedFileExts)
	{
		if ([ext length])
		{
			fileExts = [fileExts stringByAppendingFormat:@"*%@ ",ext];
		}
	}
	
	GTMScriptRunner *runner = [GTMScriptRunner runner];
	
	NSString *bashCmd = [NSString stringWithFormat:@"%@ %@ %@ > %@"
						 ,kWCScriptPath, path, fileExts, tempFileURL];
	NSLog(bashCmd);
	NSString *stdErr = nil;
	NSString *stdOut = [runner run:bashCmd standardError:&stdErr];
	NSLog(@"err:%@",stdErr);
	NSLog(@"out:%@",stdOut);
	
	if (stdErr)
	{
		NSLog(stdErr);
		return -1;
	}
	
	bashCmd = [NSString stringWithFormat:@"%@ %@", kTranslatorPath, tempFileURL];
	stdOut = [runner run:bashCmd standardError:&stdErr];
	NSLog(@"err:%@",stdErr);
	NSLog(@"out:%@",stdOut);
	
	if (stdErr)
	{
		NSLog(stdErr);
		return -1;
	}
	
	NSString *errorDesc = nil;
	NSPropertyListFormat format;
	NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"wc_out"
														  ofType:@"plist"];
	NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
	NSDictionary *tempDict = (NSDictionary *)[NSPropertyListSerialization
											  propertyListFromData:plistXML
											  mutabilityOption:NSPropertyListMutableContainersAndLeaves
											  format:&format 
											  errorDescription:&errorDesc];
	if (!tempDict)
	{
		NSLog(errorDesc);
		[errorDesc release];
		return -1;
	}
	
	NSArray *keys = [tempDict allKeys];
	NSArray *tempArray;
	NSMutableArray *outDataHolder = [NSMutableArray array];
	WCDataHolder *wcHolder;
	int i;
	for (i = 0; i < [keys count]; ++i)
	{
		if ([[keys objectAtIndex:i] isEqualToString:@"total"])
		{
			continue;
		}
		wcHolder = [[WCDataHolder alloc] init];
		tempArray = [tempDict valueForKey:[keys objectAtIndex:i]];
		wcHolder.fileURL = [keys objectAtIndex:i];
		wcHolder.lineCount = [[tempArray objectAtIndex:0] intValue];
		wcHolder.wordCount = [[tempArray objectAtIndex:1] intValue];
		wcHolder.byteCount = [[tempArray objectAtIndex:2] intValue];
		[outDataHolder addObject:wcHolder];
		[wcHolder release];
	}
	
	tempArray = [tempDict valueForKey:@"total"];
	NSAssert(tempArray != nil, @"No total lines record in plist file!");
	wcHolder = [[WCDataHolder alloc] init];
	wcHolder.fileURL = @"total";
	wcHolder.lineCount = [[tempArray objectAtIndex:0] intValue];
	wcHolder.wordCount = [[tempArray objectAtIndex:1] intValue];
	wcHolder.byteCount = [[tempArray objectAtIndex:2] intValue];
	[outDataHolder addObject:wcHolder];
	[wcHolder release];
	
	*wcData_o = outDataHolder;
	return 0;
	
#else
	int i;
	int totalLines = 0;
	NSArray *allFilePaths = [OwlSupport interestedFilesUnderPath:path];
	for (i = 0; i < [allFilePaths count]; ++i)
	{
		totalLines += [OwlWCFacility calculateLineCountForFile:[allFilePaths objectAtIndex:i]
													atFolder:path];
	}
	return totalLines;
#endif
}

+ (int)calculateLineCountForFile:(NSString *)path
						atFolder:(NSString *)folderPath
{
	GTMScriptRunner *runner = [GTMScriptRunner runnerWithBash];
	if (!runner)
	{
		NSLog(@"can not create the script runner!");
		return 0;
	}
	
	// Another way to do it is to use @"cd %@ && wc -l %@"
	NSString *bashCmd = [NSString stringWithFormat:@"wc -l %@/%@",folderPath,path];
	NSString *stdErr = nil;
	NSString *stdOut = [runner run:bashCmd standardError:&stdErr];
//	NSLog(@"err:%@",stdErr);
//	NSLog(@"out:%@",stdOut);
	
	if (!stdErr)
	{
		NSRange theRange = [stdOut rangeOfString:@" "];
		return [[stdOut substringToIndex:theRange.location] intValue];
	}
	else
	{
		NSLog(stdErr);
	}
	
	return 0;
}

@end
